package com.example.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.example.service.SysUserService;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService sysUserService() {
        return new SysUserService();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/**");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //此处把csrf校验取消，开始总是报错，就是它惹的祸
        http.csrf().disable()
        	.authorizeRequests()
                        .anyRequest().authenticated() //任何用户需要权限校验
                        .and().formLogin().loginPage("/login").failureUrl("/login?error").permitAll() 
                        .and().logout().permitAll(); 
//        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //校验注入Service
        auth.userDetailsService(sysUserService()).passwordEncoder(new PasswordEncoder(){

			@Override
			public String encode(CharSequence rawPassword) {
				Md5PasswordEncoder encoder =new Md5PasswordEncoder();
				String encodePassword = encoder.encodePassword(new StringBuilder(rawPassword).toString(), null);
				return encodePassword;
			}

			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				Md5PasswordEncoder encoder =new Md5PasswordEncoder();
				String encodePsd = encoder.encodePassword(new StringBuilder(rawPassword).toString(), null);
				return encodedPassword.equals(encodePsd);
			}
        	
        });
    }
    public static void main(String[] args) {
    	Md5PasswordEncoder encoder =new Md5PasswordEncoder();
		String one = encoder.encodePassword(new StringBuilder("111111{jt-tj}").toString(), null);
		String two = encoder.encodePassword(new StringBuilder("111111").toString(), "jt-tj");
		System.out.println(one);
		System.out.println(two);
		System.out.println(one.equals(two));
		
	}
    
}
